package cn.skylark.wcm.service.impl;


import cn.skylark.wcm.common.cos.CosConfig;
import cn.skylark.wcm.common.splitter.doc.Util;
import cn.skylark.wcm.common.util.Constants;
import cn.skylark.wcm.common.util.ReturnMap;
import cn.skylark.wcm.common.util.SFTPUtils;
import cn.skylark.wcm.common.util.UUIDHelper;
import cn.skylark.wcm.dao.FileTableDao;
import cn.skylark.wcm.entity.Filetable;
import cn.skylark.wcm.entity.User;
import cn.skylark.wcm.service.FileUploadService;
import cn.skylark.wcm.service.TenanPropertyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jcraft.jsch.*;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.request.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.io.*;
import java.util.*;

/**
 *  *Description:文件类
 *  *
 *  *Copyright:wcm
 *  *@author 武文旭
 *  *@version 1.0 
 *
 * @date 2018/01/08
 *  
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {
    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadServiceImpl.class);
    /**
     * cos
     */
    CosConfig cosConfig = new CosConfig();

    @Autowired
    public  FileTableDao fileTableDao;

    @Autowired
    public  TenanPropertyService tenanPropertyService;


    /**
     * 通过文件名查找文件
     *
     * @param filename String
     * @return
     */
    @Override
    public Filetable findByFilename(String filename) {
        LOGGER.info("通过文件名查找文件 文件名" + filename);
        Filetable filetable = new Filetable();
        filetable.setFilename(filename);
        LOGGER.info("通过文件名查找文件结束");
        return fileTableDao.selectOne(filetable);
    }

    /**
     * 增加文件信息
     *
     * @param file
     */
    @Override
    public void uploadFile(Filetable file) {
        LOGGER.info("增加文件信息开始 文件" + file);
        fileTableDao.insert(file);
        LOGGER.info("增加文件信息结束");
    }

    /**
     * 上传文件
     * 业务:上传文件到腾讯对象存储上，并将相关数据存入数据库
     *
     * @param multipartFileList List
     * @param localPath         String
     * @param realPath          String
     * @param user              User
     * @param father            String
     * @param para              String
     * @param type              Integer
     * @return
     * @Exception 数据库连接异常
     */
    @Override
    public Map<String, Object> uploadFileLocal(List<MultipartFile> multipartFileList, String localPath,
                                               String realPath, User user, String father, String para, Integer type) {
        LOGGER.info("文件上传开始 文件:" + multipartFileList + "文件地址:" + localPath + "服务器地址:" + realPath +
                "用户:" + user + "父文件路径:" + father + "文件类型:" + para + "所在系统:" + type);
        Map<String, Object> map = new HashMap<>();
        // 腾讯云对象存储COS调用
        COSClient cos = cosConfig.getCosClient(tenanPropertyService, user);
        String[] localpathlist = localPath.split("\\|");
        int i = 0;
        try {
            for (MultipartFile multipartFile : multipartFileList) {
                String name = null;
                String filename;
                if (!"undefined".equals(localpathlist[i])) {
                    //如果不为undefined 就是相对路径
                    filename = father + "" + localpathlist[i];
                    name = localpathlist[i].substring(localpathlist[i].lastIndexOf("/")+1, localpathlist[i].lastIndexOf("."));

                } else {
                    //如果是undefined 就是文件名 xx.xx
                    filename = multipartFile.getOriginalFilename();
                    name = filename;
                    LOGGER.info(filename);
                }

                // 本地用于存放文件的路径
                InputStream input;
                input = multipartFile.getInputStream();
                String localwritePath = realPath + "upload/" + para + "/" + filename;
                //将流转换为String
                //1.如果是doc文档

                File file = new File(localwritePath);
                FileUtils.write(file, "");
                FileOutputStream os = new FileOutputStream(localwritePath);
                byte[] buffer = new byte[1024 * 1024];
                int n = 0;
                while (-1 != (n = input.read(buffer))) {
                    os.write(buffer, 0, n);
                }

                os.flush();
                os.close();
                input.close();
                if (!"undefined".equals(localpathlist[i])) {
                    String tmpPath = "/" + para + "/";
                    CreateFolderRequest createFolderRequest =
                            new CreateFolderRequest(cosConfig.bucketName, tmpPath);
                    String createFolderRet = cos.createFolder(createFolderRequest);
                    LOGGER.info("----------腾讯对象存储新建文件目录====" + createFolderRet + "---------");
                }
                File file1 = new File(localwritePath);
                InputStream is = new FileInputStream(file1);
                String htmlStr="";
                if (type == 1) {
                    htmlStr = getHTMLTEXT(is);
                }
                String newFIlename = UUIDHelper.getUUID() + filename.substring(filename.lastIndexOf("."));
                // 腾讯对象存储写入文件
                UploadFileRequest uploadFileRequest =
                        new UploadFileRequest(cosConfig.bucketName, "/" + para + "/" + newFIlename, localwritePath);
                String uploadFileRet = cos.uploadFile(uploadFileRequest);
                LOGGER.info("----------腾讯对象存储上传文件====" + uploadFileRet + "---------");
                JSONObject myJson = new JSONObject();
                myJson = JSONObject.fromObject(uploadFileRet);
                Map uploadMap = myJson;
                if (!uploadMap.get("code").toString().equals("0")) {
                    map.put("code", 1);
                    map.put("message", "文件上传失败");
                    return map;
                }
                //bool 为true 腾讯对象存储上传成功
                if (uploadMap.get("code").toString().equals("0")) {
                    //将html转换为txt
                    String uuid = newFIlename;
                    JSONObject data = JSONObject.fromObject(uploadMap.get("data"));
                    Map dataMap = data;
                    // 删除本地临时文件
                    File delfile = new File(localwritePath);
                    delfile.delete();
                    String tmpFilename;
                    String llocalpath;
                    if (!"undefined".equals(localpathlist[i])) {
                       // FileUtils.deleteDirectory(new File(delfile.getParent()));
                        tmpFilename = filename.substring(filename.lastIndexOf("/") + 1,
                                filename.lastIndexOf("."));
                        llocalpath = filename.substring(0, filename.lastIndexOf("/"));
                    } else {
                        tmpFilename = filename.substring(0, filename.lastIndexOf("."));
                        llocalpath = "";
                    }
                    //自己定义的方法目的是为了创建文件夹数据
                    if (!"undefined".equals(localpathlist[i])) {
                        this.createFolder(cosConfig.tenanid, cosConfig.userid, localPath, father, type);
                        //判断是否重复
                        Filetable newFile = new Filetable();
                        newFile.setFilename(tmpFilename);
                        newFile.setLocalpath(father + llocalpath + "/");
                        newFile.setSuffix((filename.substring(filename.lastIndexOf(".") + 1)).toLowerCase());
                        newFile.setTenanid(cosConfig.tenanid);
                        newFile.setUserid(cosConfig.userid);
                        newFile.setType(type);
                        newFile.setDelflg(0);
                        int t = fileTableDao.selectCount(newFile);
                        if (t != 0) {
                            map.put("code", 1);
                            map.put("message", "该目录下已经存在此文件");
                            return map;
                        } else {
                            // 数据库存储
                            newFile.setFilename(tmpFilename);
                            newFile.setLocalpath(llocalpath + "/");
                            newFile.setRemotepath(dataMap.get("access_url").toString());
                            newFile.setSize(String.valueOf(multipartFile.getSize()));
                            newFile.setSuffix((filename.substring(filename.lastIndexOf(".") + 1)).toLowerCase());
                            newFile.setTenanid(cosConfig.tenanid);
                            newFile.setUserid(cosConfig.userid);
                            newFile.setType(type);
                            newFile.setDelflg(0);
                            uploadFile(newFile);
                        }
                    } else {
                        // 数据库存储
                        Filetable newFile = new Filetable();
                        newFile.setFilename(tmpFilename);
                        newFile.setLocalpath(father + llocalpath + "/");
                        newFile.setSuffix((filename.substring(filename.lastIndexOf(".") + 1)).toLowerCase());
                        newFile.setTenanid(cosConfig.tenanid);
                        newFile.setUserid(cosConfig.userid);
                        newFile.setType(1);
                        newFile.setDelflg(0);
                        int t = fileTableDao.selectCount(newFile);
                        if (t != 0) {
                            map.put("code", 1);
                            map.put("message", "该目录下已经存在此文件");
                            return map;
                        } else {
                            // 数据库存储
                            newFile.setFilename(tmpFilename);
                            if (father == "") {
                                newFile.setLocalpath("");
                            }
                            newFile.setLocalpath(father);
                            newFile.setRemotepath(dataMap.get("access_url").toString());
                            newFile.setSize(String.valueOf(multipartFile.getSize()));
                            newFile.setSuffix(filename.substring(filename.lastIndexOf(".") + 1));
                            newFile.setTenanid(cosConfig.tenanid);
                            newFile.setUserid(cosConfig.userid);
                            newFile.setDelflg(0);
                            newFile.setType(type);
                            uploadFile(newFile);
                        }
                    }
                    if (type == 1) {
                        uploadOrginalTxt(htmlStr, name, uuid, user);
                    }
                } else {
                    map.put("code", 1);
                    map.put("message", "文件上传失败");
                    return map;
                }
                i++;
            }
            map.put("code", 0);
            map.put("message", "文件上传成功");
        } catch (Exception e) {
            map.put("code", 1);
            map.put("message", new String(e.getCause().toString().replaceAll(":", "|")));
        }
        return map;
    }

    /**
     * 自动生成文件夹
     * 业务：给出了相对路径，通过相对路径在数据库想其父文件夹
     *
     * @param tenanid
     * @param userid
     * @param path
     * @param father
     * @param type
     */
    @Override
    public void createFolder(Integer tenanid, Integer userid, String path, String father, Integer type) {
        LOGGER.info("通过相对地址在数据库创建文件夹 租户id=" + tenanid + "用户id=" + userid + "地址" + path);
        String newPath = path.replaceAll("undefined\\|","");
        String[] str = newPath.split("\\|");
        //现在的路径有种情况无法处理，用户创建一个空文件夹，在里面再创建一个文件夹，里面放
        //文件，路径截取出来的只会创建二级文件夹，无法创建一级文件夹，通过StringBuffer的apperd方法进项
        //字符串增加，保证路径的完整
        String[] array = new String[str.length];
        for (int i = 0; i < str.length; i++) {
            String tmpPath = str[i].substring(0, str[i].lastIndexOf("/"));
            array[i] = tmpPath;
        }
        List<String> list = new ArrayList();
        for (String message : array) {
            if (message.indexOf("/") == -1) {
                list.add(message + "/");
            } else {
                String[] aa = message.split("/");
                StringBuffer stringBuffer = new StringBuffer();
                for (int i = 0; i < aa.length; i++) {
                    stringBuffer.append(aa[i] + "/");
                    list.add(stringBuffer.toString());
                }
            }
        }
        //去重
        Set set = new HashSet();
        List newList = new ArrayList();
        for (String cd : list) {
            if (set.add(cd)) {
                newList.add(cd);
            }
        }
        String[] arrayResult = (String[]) newList.toArray(new String[newList.size()]);
        String tmpFilename = null;
        String llocalpath = null;
        for (int i = 0; i < arrayResult.length; i++) {
            String string = arrayResult[i];
            String strArray = string.substring(0, string.lastIndexOf("/"));
            if (strArray.lastIndexOf("/") < 1) {
                System.out.println(strArray);
                tmpFilename = strArray;
                llocalpath = "";
                this.insertFolder(tmpFilename, llocalpath, tenanid, userid, type, father);
            } else {
                String name = strArray.substring(strArray.lastIndexOf("/") + 1, strArray.length());
                String pathL = strArray.substring(0, strArray.lastIndexOf("/"));
                tmpFilename = name;
                llocalpath = pathL + "/";
                this.insertFolder(tmpFilename, llocalpath, tenanid, userid, type, father);
            }
        }
        LOGGER.info("自动生成文件夹结束");
    }

    /**
     * 新建文件夹信息进数据库
     * 业务：将文件夹相关信息插入数据库
     *
     * @param tmpFilename
     * @param llocalpath
     * @param tenanid
     * @param userid
     * @param type
     */
    @Override
    public void insertFolder(String tmpFilename, String llocalpath, Integer tenanid, Integer userid, Integer type, String father) {
        LOGGER.info("新建文件夹信息进数据库开始 文件名" + tmpFilename + "地址" + llocalpath + "租户id"
                + tenanid + "用户id" + userid + "系统号" + type);
        Filetable filetable = new Filetable();
        filetable.setLocalpath(father + "" + llocalpath);
        filetable.setFilename(tmpFilename);
        filetable.setSuffix("");
        filetable.setType(type);
        filetable.setTenanid(tenanid);
        filetable.setUserid(userid);
        filetable.setType(type);
        filetable.setDelflg(0);
        Integer count = this.selectFolderById(filetable);
        if (count < 1) {
            Filetable newFile = new Filetable();
            newFile.setFilename(tmpFilename);
            newFile.setLocalpath(father + llocalpath);
            newFile.setRemotepath("");
            newFile.setSize("");
            newFile.setSuffix("");
            newFile.setTenanid(tenanid);
            newFile.setUserid(userid);
            newFile.setType(type);
            newFile.setDelflg(0);
            uploadFile(newFile);
            LOGGER.info("新建文件夹信息进数据库结束");
        }
    }


    /**
     * 根据条件进行查询该文件夹是否存在
     * 业务：判断文件夹是否存在
     *
     * @param filetable 文件实体类
     * @return
     */
    @Override
    public Integer selectFolderById(Filetable filetable) {
        LOGGER.info("查询文件夹是否存在开始" + "文件:" + filetable);
        Integer count = fileTableDao.selectCount(filetable);
        LOGGER.info("查询文件夹是否存在结束");
        return count;
    }

    /**
     * 新建文件夹
     * 业务：页面点击的新建文件夹
     *
     * @param filetable 文件的实体类
     */
    @Override
    public void saveFolder(Filetable filetable) {
        LOGGER.info("新建文件夹开始" + filetable);
        filetable.setDelflg(0);
        fileTableDao.insert(filetable);
        LOGGER.info("新建文件夹结束");
    }

    /**
     * 取得数据库中的文件列表
     * 业务：同租户id获取文件列表
     *
     * @param tenanid 租户ID
     * @return 数据库中文件列表
     */
    @Override
    public ReturnMap getFileByTenanid(Integer tenanid) {
        LOGGER.info("取得数据库中的文件列表开始 租户id" + tenanid);
        ReturnMap ret = new ReturnMap();
        List<Filetable> filetableList = fileTableDao.getFileByTenanid(tenanid);
        ret.setFlg(0);
        ret.setMessage("success");
        ret.setData(JSONArray.fromObject(filetableList).toString());
        LOGGER.info("取得数据库中的文件列表结束");
        return ret;
    }

    /**
     * 网页生成的html上传
     * 业务：将通过网页生成的html文件上传至腾讯对象存储，
     * 并将相关信息存入数据库
     *
     * @param htmlfile
     * @param htmlname
     * @param user
     * @param fatherPath
     * @param realPath
     * @return
     */
    @Override
    public Map<String, Object> uploadFileHtmlLocal(String htmlfile, String htmlname, User user, String fatherPath, String realPath) {
        LOGGER.info("网页生成的html上传 html文件:" + htmlfile + "文件名:" + htmlname + "服务器地址:" + realPath +
                "用户:" + user);
        Map<String, Object> map = new HashMap<>();
        // 腾讯云对象存储COS调用
        COSClient cos = cosConfig.getCosClient(tenanPropertyService, user);
        Integer type = 1;
        String htmlfileLocal = htmlfile;
        try {
            String name = htmlname.substring(0, htmlname.lastIndexOf("."));
            String filename = htmlname;
            // 本地用于存放文件的路径
            String localwritePath = realPath + "upload" + File.separator + "html" + File.separator + filename;
            //写入服务器本地文件夹
            ByteArrayInputStream input = new ByteArrayInputStream(htmlfile.getBytes());
            File file = new File(localwritePath);
            FileUtils.write(file, "");
            FileOutputStream os = new FileOutputStream(localwritePath);
            byte[] buffer = new byte[1024 * 1024];
            int n = 0;
            while (-1 != (n = input.read(buffer))) {
                os.write(buffer, 0, n);
            }
            os.flush();
            os.close();
            input.close();
            // 腾讯对象存储新建文件目录
            String tmpPath = "/html/";
            CreateFolderRequest createFolderRequest =
                    new CreateFolderRequest(cosConfig.bucketName, tmpPath);
            String createFolderRet = cos.createFolder(createFolderRequest);
            LOGGER.info("----------腾讯对象存储新建文件目录====" + createFolderRet + "---------");
            String newFIlename = UUIDHelper.getUUID() + filename.substring(filename.lastIndexOf("."));
            // 腾讯对象存储写入文件
            UploadFileRequest uploadFileRequest =
                    new UploadFileRequest(cosConfig.bucketName, "/html/" + newFIlename, localwritePath);
            String uploadFileRet = cos.uploadFile(uploadFileRequest);
            LOGGER.info("----------腾讯对象存储上传文件====" + uploadFileRet + "---------");
            JSONObject myJson = new JSONObject();
            myJson = JSONObject.fromObject(uploadFileRet);
            Map uploadMap = myJson;
            if (uploadMap.get("code").toString().equals("0")) {
                //html转txt
                String uuid = newFIlename;
                //腾讯上传成功
                LOGGER.info("上传成功了");
                JSONObject data = JSONObject.fromObject(uploadMap.get("data"));
                // 删除本地临时文件
                Map dataMap = data;
                File delfile = new File(localwritePath);
                delfile.delete();
                //自己定义的方法目的是为了创建文件夹数据
                Filetable newFile = new Filetable();
                newFile.setFilename(filename.substring(0, filename.lastIndexOf(".")));
                newFile.setLocalpath(fatherPath);
                newFile.setRemotepath(dataMap.get("access_url").toString());
                newFile.setSize(String.valueOf(htmlfile.getBytes("UTF-8").length));
                newFile.setSuffix(filename.substring(filename.lastIndexOf(".") + 1));
                newFile.setTenanid(cosConfig.tenanid);
                newFile.setUserid(cosConfig.userid);
                newFile.setDelflg(0);
                newFile.setType(type);
                uploadFile(newFile);
                map.put("code", 0);
                map.put("message", "html上传成功");
                if (type == 1) {
                    uploadOrginalTxt(htmlfile, name, uuid, user);
                }
            } else {
                map.put("code", 1);
                map.put("message", "html上传失败");
                return map;
            }
            LOGGER.info("网页生成的html上传结束");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 2);
            map.put("message", "html上传异常");
        }
        return map;
    }

    /**
     * 获取该租户下的已经用掉的储存空间
     *
     * @param tenanid 租户id
     * @return
     */
    @Override
    public String getTotalSize(Integer tenanid) {
        LOGGER.info("获取该租户下的已经用掉的储存空间开始 租户id" + tenanid);
        String Size = fileTableDao.getTotalSize(tenanid);
        LOGGER.info("获取该租户下的已经用掉的储存空间结束");
        return Size;
    }


    /**
     * 本地视频文件上传用
     *
     * @param multipartFileList 文件列表
     * @param localPath         本地上传路径
     * @param realPath          服务器临时文件目录
     * @return ReturnMap
     */
    @Override
    public ReturnMap uploadVideoFileLocal(List<MultipartFile> multipartFileList, String localPath,
                                          String realPath, User user, String father, Integer type) {
        LOGGER.info("获取该租户下的已经用掉的储存空间开始");
        ReturnMap ret = new ReturnMap();
        // 腾讯云对象存储COS调用
        COSClient cos = cosConfig.getCosClient(tenanPropertyService, user);
        String[] localpathlist = localPath.split("\\|");
        int i = 0;
        try {
            for (MultipartFile multipartFile : multipartFileList) {
                String filename;
                if (!"undefined".equals(localpathlist[i])) {
                    //如果不为undefined 就是相对路径
                    filename = father + "" + localpathlist[i];
                } else {
                    //如果是undefined 就是文件名 xx.xx
                    filename = multipartFile.getOriginalFilename();
                    LOGGER.info(filename);
                }
                // 本地用于存放文件的路径
                InputStream input = multipartFile.getInputStream();
                String localwritePath = realPath + "upload/video/" + filename;

                File file = new File(localwritePath);
                FileUtils.write(file, "");
                FileOutputStream os = new FileOutputStream(localwritePath);
                byte[] buffer = new byte[1024 * 1024];
                int n = 0;
                while (-1 != (n = input.read(buffer))) {
                    os.write(buffer, 0, n);
                }
                os.flush();
                os.close();
                input.close();
                // 腾讯对象存储新建文件目录
                if (!"undefined".equals(localpathlist[i])) {
                    String tmpPath = "/video/";
                    CreateFolderRequest createFolderRequest =
                            new CreateFolderRequest(cosConfig.bucketName, tmpPath);
                    String createFolderRet = cos.createFolder(createFolderRequest);
                    LOGGER.info("----------腾讯对象存储新建文件目录====" + createFolderRet + "---------");
                }
                String newFIlename = UUIDHelper.getUUID() + filename.substring(filename.lastIndexOf("."));
                // 腾讯对象存储写入文件
                UploadFileRequest uploadFileRequest =
                        new UploadFileRequest(cosConfig.bucketName, "/video/" + newFIlename, localwritePath);
                String uploadFileRet = cos.uploadFile(uploadFileRequest);

                LOGGER.info("----------腾讯对象存储上传文件====" + uploadFileRet + "---------");
                JSONObject myJson = new JSONObject();
                myJson = JSONObject.fromObject(uploadFileRet);
                Map uploadMap = myJson;
                if (uploadMap.get("code").toString().equals("0")) {
                    //腾讯上传成功
                    LOGGER.info("视频上传成功了");
                    JSONObject data = JSONObject.fromObject(uploadMap.get("data"));
                    Map dataMap = data;
                    // 删除本地临时文件
                    File delfile = new File(localwritePath);
                    delfile.delete();
                    String tmpFilename;
                    String llocalpath;
                    if (!"undefined".equals(localpathlist[i])) {
                        FileUtils.deleteDirectory(new File(delfile.getParent()));
                        tmpFilename = filename.substring(filename.lastIndexOf("/") + 1,
                                filename.lastIndexOf("."));
                        llocalpath = filename.substring(0, filename.lastIndexOf("/"));
                    } else {
                        tmpFilename = filename.substring(0, filename.lastIndexOf("."));
                        llocalpath = "";
                    }
                    // 数据库存储
                    Filetable newFile = new Filetable();
                    newFile.setFilename(tmpFilename);
                    newFile.setLocalpath("");
                    newFile.setRemotepath(dataMap.get("access_url").toString());
                    newFile.setSize(String.valueOf(multipartFile.getSize()));
                    newFile.setSuffix(filename.substring(filename.lastIndexOf(".") + 1));
                    newFile.setTenanid(cosConfig.tenanid);
                    newFile.setUserid(cosConfig.userid);
                    newFile.setType(type);
                    newFile.setDelflg(0);
                    uploadFile(newFile);
                } else {
                    ret.setFlg(0);
                    ret.setMessage("视频上传失败");
                    return ret;
                }
                i++;
            }
            ret.setFlg(0);
            ret.setMessage("视频上传成功");
        } catch (Exception e) {
            ret.setFlg(1);
            ret.setMessage(new String(e.getCause().toString().replaceAll(":", "|")));
        }
        return ret;
    }

    /**
     * 获取html网页的链接
     * 业务：通过id获取到网页的链接
     *
     * @param filetable
     * @return
     */
    @Override
    public Filetable getHtmlContent(Filetable filetable) {
        LOGGER.info("获取html网页的内容开始 文件" + filetable);
        Filetable filetable1 = fileTableDao.selectOne(filetable);
        LOGGER.info("获取html网页的内容结束");
        return filetable1;
    }

    /**
     * 分页查询获取所有网页管理信息
     * 业务：查询条件是userid和tenanid
     *
     * @param filetable
     * @param flag
     * @param start
     * @param length
     * @return
     */
    @Override
    public Map<String, Object> selectByPage(Filetable filetable, String flag, String searchValue, int start, int length) {
        LOGGER.info("分页查询获取所有网页管理信息--文件" + filetable + "启始页" + start + "条数" + length);
        Map<String, Object> map = new HashMap<>();
        int page = start / length + 1;
        // 分页查询
        PageHelper.startPage(page, length);
        //根目录没有文件夹，但子文件夹已删除的文件
        Example example = new Example(Filetable.class);
        Example.Criteria criteria = example.createCriteria();
        //条件查询
        if (!StringUtils.isEmpty(searchValue)) {
            criteria.andLike("filename", "%" + searchValue + "%");
        }
        if ("0".equals(flag)) {
            criteria.andEqualTo("localpath", "");
            criteria.andEqualTo("userid", filetable.getUserid());
            criteria.andEqualTo("tenanid", filetable.getTenanid());
            criteria.andEqualTo("type", 1);
            criteria.andEqualTo("delflg", 0);
            example.setOrderByClause("updatetime desc");
        } else if ("1".equals(flag)) {
            criteria.andEqualTo("type", 1);
            criteria.andEqualTo("delflg", 0);
            criteria.andEqualTo("localpath", "");
            example.setOrderByClause("updatetime desc");
        }
        List<Filetable> filetableList = fileTableDao.selectByExample(example);

        // 分页查询
        PageHelper.startPage(page, length);
        LOGGER.info("分页查询获取所有网页管理信息结束");
        PageInfo pageInfo = new PageInfo<>(filetableList);
        map.put("recordsTotal", pageInfo.getTotal());
        map.put("recordsFiltered", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }

    /**
     * 分页查询获取所有网页管理文件夹内信息
     * 业务：查询条件是userid和tenanid filename和localpath
     *
     * @param filetableId
     * @param start
     * @param length
     * @return
     */
    @Override
    public Map<String, Object> selectByPageFolder(Filetable filetableId, String searchValue, int start, int length) {
        LOGGER.info("获取当前目录的内容 父id" + filetableId.getId() + "启始页" + start + "条数" + length);
        Map<String, Object> map = new HashMap<>();
        try {
            Filetable filetable = fileTableDao.selectOne(filetableId);
            int page = start / length + 1;
            Example example = new Example(Filetable.class);
            Example.Criteria criteria = example.createCriteria();
            if (filetable.getLocalpath() == null) {
                filetable.setLocalpath("");
            }
            if (StringUtil.isNotEmpty(searchValue)) {
                criteria.andLike("filename", "%" + searchValue + "%");
            }
            criteria.andEqualTo("localpath", filetable.getLocalpath() + "" + filetable.getFilename() + "/");
            criteria.andEqualTo("type", filetable.getType());
            criteria.andEqualTo("userid", filetable.getUserid());
            criteria.andEqualTo("delflg", 0);
            example.setOrderByClause("updatetime desc");
            // 分页查询
            PageHelper.startPage(page, length);
            List<Filetable> filetableList = fileTableDao.selectByExample(example);
            LOGGER.info("分页查询获取所有网页管理文件夹内信息");
            PageInfo<Filetable> pageInfo = new PageInfo<>(filetableList);
            map.put("recordsTotal", pageInfo.getTotal());
            map.put("recordsFiltered", pageInfo.getTotal());
            map.put("data", pageInfo.getList());
            String localpath = "";
            String path = "";
            if (filetable.getLocalpath() == null || "".equals(filetable.getLocalpath())) {
                localpath = ">";
            } else {
                String orginLocalpath = filetable.getLocalpath().replaceAll("/", ">");
                localpath = ">" + orginLocalpath;
                LOGGER.info("localpath" + localpath);
            }
            path = localpath + filetable.getFilename();
            map.put("localpath", path);
            map.put("code", 0);
            map.put("message", "获取用户文件列表成功");
            LOGGER.info("获取当前目录的内容成功");
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 2);
            map.put("mesage", "数据异常");
            LOGGER.info("获取当前目录的内容失败" + e);
            return map;
        }
    }

    /**
     * 文件删除
     *
     * @param filename 文件名称包含相对路径
     * @return 返回结果
     */
    @Override
    public ReturnMap deleteFile(String filename, User user) {
        LOGGER.info("文件删除开始 文件名" + filename + "用户信息" + user);
        ReturnMap ret = new ReturnMap();
        try {
            // 腾讯云对象存储COS调用
            COSClient cos = cosConfig.getCosClient(tenanPropertyService, user);

            DelFileRequest delFileRequest = new DelFileRequest(cosConfig.bucketName, "/" + filename);
            String delFileRet = cos.delFile(delFileRequest);
            LOGGER.info("----------腾讯对象存储删除文件====" + delFileRet + "---------");

            // 数据库存储
            Filetable newFile = new Filetable();
            newFile.setLocalpath(filename);
            deleteFile(newFile);

            ret.setFlg(0);
            ret.setMessage("删除成功");
        } catch (Exception e) {
            ret.setFlg(1);
            ret.setMessage(new String(e.getCause().toString().replaceAll(":", "|")));
            LOGGER.info("删除失败");
        }
        LOGGER.info("删除成功");
        return ret;
    }

    ;

    /**
     * 删除文件
     * 业务：删除文件通过id
     *
     * @param doc Filetable
     */
    @Override
    public void deleteFile(Filetable doc) {
        LOGGER.info("删除文件开始 文件" + doc);
        Example example = new Example(Filetable.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("localpath", doc.getLocalpath());
        LOGGER.info("删除文件结束");
        fileTableDao.deleteByExample(example);
    }

    /**
     * 查询文件是否存在
     * 业务：count>0表示存在
     *
     * @param filetable
     * @return
     */
    @Override
    public Integer selectFileName(Filetable filetable) {
        LOGGER.info("查询文件是否存在开始 文件" + filetable);
        Integer count = fileTableDao.selectCount(filetable);
        LOGGER.info("查询文件是否存在结束");
        return count;
    }

    /**
     * 下载文件
     *
     * @param id       文件id
     * @param realPath 真实路径
     * @param user     用户信息
     * @param type     文件夹类型
     * @return
     */
    @Override
    public ReturnMap downloadFile(Integer id, String realPath, User user, String type) {
        LOGGER.info("下载文件开始 文件id:" + id + "服务器路径:" + realPath + "用户信息:" + user + "文件类型:" + type);
        ReturnMap ret = new ReturnMap();
        try {
            Filetable filetable = new Filetable();
            filetable.setId(id);
            Filetable filetableContext = fileTableDao.selectOne(filetable);
            String remotepath = filetableContext.getRemotepath();
            String localpath = filetableContext.getLocalpath();
            String name = filetableContext.getFilename();
            String suffix = filetableContext.getSuffix();
            String path = remotepath.substring(remotepath.lastIndexOf("/"));
            String servicepath = type + path;
            // 腾讯云对象存储COS调用
            COSClient cos = cosConfig.getCosClient(tenanPropertyService, user);
            GetFileInputStreamRequest getFileInputStreamRequest = new GetFileInputStreamRequest(
                    cosConfig.bucketName,
                    servicepath);
            InputStream input = cos.getFileInputStream(getFileInputStreamRequest);

            LOGGER.info("====获取文件成功====");
            File file = new File(realPath + "upload/" + type + "/" + localpath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String filepath = realPath + "upload/" + type + "/" + localpath + name + "." + suffix;
            LOGGER.info("filepath" + filepath);
            FileUtils.write(new File(filepath), "");
            FileOutputStream os = new FileOutputStream(filepath);
            byte[] buffer = new byte[1024];
            int n = 0;
            while (-1 != (n = input.read(buffer))) {
                os.write(buffer, 0, n);
            }
            os.flush();
            os.close();
            input.close();
            LOGGER.info("下载文件结束");
        } catch (Exception e) {
            ret.setFlg(1);
            ret.setMessage(new String(e.getCause().toString().replaceAll(":", "|")));
        }
        return null;
    }

    /**
     * 下载远端的html，没有文件夹的形式
     *
     * @param id       文件id
     * @param realPath 真实路径
     * @param user     用户信息
     * @param type     类型
     * @return
     */
    @Override
    public ReturnMap downloadRemoteHtml(Integer id, String realPath, User user, String type) {
        LOGGER.info("下载文件开始 文件id:" + id + "服务器路径:" + realPath + "用户信息:" + user + "文件类型:" + type);
        ReturnMap ret = new ReturnMap();
        try {
            Filetable filetable = new Filetable();
            filetable.setId(id);
            Filetable filetableContext = fileTableDao.selectOne(filetable);
            String remotepath = filetableContext.getRemotepath();
            String newReotePath = remotepath.substring(remotepath.lastIndexOf("/"), remotepath.lastIndexOf("."));
            String localpath = filetableContext.getLocalpath();
            String name = filetableContext.getFilename();
            String suffix = filetableContext.getSuffix();
            String path = remotepath.substring(remotepath.lastIndexOf("/"));
            String servicepath = type + path;

            File haveflg = new File(realPath + "upload/" + type + newReotePath + "." + suffix);
            if (!haveflg.exists()) {
                // 腾讯云对象存储COS调用
                COSClient cos = cosConfig.getCosClient(tenanPropertyService, user);
                GetFileInputStreamRequest getFileInputStreamRequest = new GetFileInputStreamRequest(
                        cosConfig.bucketName,
                        servicepath);
                InputStream input = cos.getFileInputStream(getFileInputStreamRequest);

                LOGGER.info("====获取文件成功====");
                File file = new File(realPath + "upload/" + type);
                if (!file.exists()) {
                    file.mkdirs();
                }
                String filepath = realPath + "upload/" + type + newReotePath + "." + suffix;
                LOGGER.info("filepath" + filepath);
                FileUtils.write(new File(filepath), "");
                FileOutputStream os = new FileOutputStream(filepath);
                byte[] buffer = new byte[1024];
                int n = 0;
                while (-1 != (n = input.read(buffer))) {
                    os.write(buffer, 0, n);
                }
                os.flush();
                os.close();
                input.close();
            }
            LOGGER.info("下载文件结束");
        } catch (Exception e) {
            ret.setFlg(1);
            ret.setMessage(new String(e.getCause().toString().replaceAll(":", "|")));
        }
        return null;
    }

    /**
     * 检查文件是否存在
     *
     * @param filename
     * @param tenanid
     * @param userid
     * @param type
     * @return
     */
    @Override
    public boolean selectFileRepeat(String filename, Integer tenanid, Integer userid, Integer type) {
        LOGGER.info("检查文件是否存在开始 文件名" + filename + "租户id" + tenanid + "用户id" + userid + "文件夹类型" + type);
        Filetable filetable = new Filetable();
        filetable.setUserid(userid);
        filetable.setTenanid(tenanid);
        filetable.setFilename(filename.substring(filename.lastIndexOf("/") + 1, filename.lastIndexOf(".")));
        filetable.setDelflg(0);
        filetable.setSuffix(filename.substring(filename.lastIndexOf(".") + 1));
        if ((filename.lastIndexOf("/") < 1)) {
            filetable.setLocalpath("");
        } else {
            filetable.setLocalpath(filename.substring(0, filename.lastIndexOf("/") + 1));
        }
        Integer count = selectFileName(filetable);
        if (count > 0) {
            return false;
        }
        LOGGER.info("检查文件是否存在结束");
        return true;
    }


    /**
     * * 回退 html管理
     * 业务:通过当前文件的localpath,找到相同的并返回
     *
     * @param filetable
     * @param searchValue
     * @param start
     * @param length
     * @return
     */
    @Override
    public PageInfo<Filetable> backoffHtml(Filetable filetable, String flag, String searchValue, Integer start, Integer length) {
        LOGGER.info("分页获取返回上一级文件信息--文件" + filetable + "启始页" + start + "条数" + length);
        Map<String, Object> map = new HashMap<>();
        int page = start / length + 1;
        Example example = new Example(Filetable.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotEmpty(searchValue)) {
            criteria.andLike("filename", "%" + searchValue + "%");
        }
        criteria.andEqualTo("userid", filetable.getUserid());
        criteria.andEqualTo("tenanid", filetable.getTenanid());
        criteria.andEqualTo("type", filetable.getType());
        criteria.andEqualTo("delflg", filetable.getDelflg());
        criteria.andEqualTo("localpath", filetable.getLocalpath());
        example.setOrderByClause("updatetime desc");
        // 分页查询
        PageHelper.startPage(page, length);
        List<Filetable> htmllist = fileTableDao.selectByExample(example);
        LOGGER.info("分页获取返回上一级文件信息结束");
        return new PageInfo<>(htmllist);
    }

    /**
     * 上传已经拆分的文件
     * 业务：1.根据本地路径，判断上传的文件是txt格式的还是html格式的，然后进行分类上传。
     * 2.主要是上传成功之后进行保存到数据库中。
     *
     * @param filename 本地的文件路径
     * @param realPath 真实路径
     */
    @Override
    public Filetable uploadConvert(String filename, String realPath, User user) {
        LOGGER.info("上传已经拆分过的文件开始====filename" + filename + "===relPath===" + realPath + "===user===" + user);
        ReturnMap ret = new ReturnMap();
        Filetable newFile = new Filetable();
        COSClient cos = cosConfig.getCosClient(tenanPropertyService, user);

        // 腾讯对象存储新建文件目录
        try {
            LOGGER.info("对象存在目录");
            //判断上传的是什么类型文件
            String tmpPath;
            String suffix = filename.substring(filename.lastIndexOf("."));
            if (suffix.endsWith("txt")) {
                tmpPath = "/txt/";
            } else {
                tmpPath = "/html/";
            }
            CreateFolderRequest createFolderRequest =
                    new CreateFolderRequest(cosConfig.bucketName, tmpPath);
            String createFolderRet = cos.createFolder(createFolderRequest);
            LOGGER.info("----------腾讯对象存储新建文件目录====" + createFolderRet + "---------");
            String newFIlename = UUIDHelper.getUUID() + filename.substring(filename.lastIndexOf("."));
            // 腾讯对象存储写入文件
            UploadFileRequest uploadFileRequest =
                    new UploadFileRequest(cosConfig.bucketName, tmpPath + newFIlename, filename);
            String uploadFileRet = cos.uploadFile(uploadFileRequest);
            LOGGER.info("----------腾讯对象存储上传文件====" + uploadFileRet + "---------");
            JSONObject myJson = JSONObject.fromObject(uploadFileRet);
            Map uploadMap = myJson;
            if (uploadMap.get("code").toString().equals("0")) {
                JSONObject data = JSONObject.fromObject(uploadMap.get("data"));
                Map dataMap = data;
                //获取本地文件大小。
                File delfile = new File(filename);
                String size = String.valueOf(delfile.length());
                //得到relpath的路径中\的个数,为了拆分到目录
                String replacePath = filename.replaceAll("\\\\", "/");
                String newPath = replacePath.replaceAll("/mnt/wcm/upload/file/", "");
                LOGGER.info("转换后===" + newPath);
                String fileName = newPath.substring(newPath.lastIndexOf("/") + 1, newPath.indexOf("."));
                LOGGER.info("输出的文件名===" + fileName);
                String newlocalpath = null;
                if (newPath.contains("/")) {
                    newlocalpath = newPath.substring(0, newPath.lastIndexOf("/")) + "/";
                } else {
                    newlocalpath = "";
                }
                //判断是txt还是html上传
                Integer type = 1;
                if (suffix.endsWith("txt")) {
                    type = 3;
                }
                LOGGER.info("==进数据库的fileName===" + fileName);
                LOGGER.info("==进数据库的newlocalpath===" + newlocalpath);
                LOGGER.info("==进数据库的type===" + type);
                //保存文件到数据库中
                newFile.setFilename(fileName);
                newFile.setLocalpath(newlocalpath);
                newFile.setRemotepath(dataMap.get("access_url").toString());
                newFile.setSize(size);
                newFile.setSuffix(filename.substring(filename.lastIndexOf(".") + 1));
                newFile.setTenanid(cosConfig.tenanid);
                newFile.setUserid(cosConfig.userid);
                newFile.setDelflg(0);
                newFile.setType(type);
                uploadFile(newFile);
                //然后要得到所上传的
            } else {
                ret.setFlg(1);
                ret.setMessage("上传到云服务失败");
                throw new Exception("文件上传失败");
            }
            ret.setFlg(0);
            ret.setMessage("上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            ret.setFlg(1);
            ret.setMessage(new String(e.getCause().toString().replaceAll(":", "|")));
        }
        return newFile;
    }

    /**
     * 删除文件夹下的所有文件和文件夹
     * 1.判断是文件还是文件夹，如果是文件夹的话，再次调用方法，进行遍历的删除，
     * 只到每个文件都删除。
     *
     * @param file 文件的真实路径的文件
     */
    @Override
    public void deleteAllFile(File file) {
        LOGGER.info("删除文件夹下的文件开始===" + "file====" + file);
        if (file.isFile() || file.list().length == 0) {
            file.delete();
        } else {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteAllFile(files[i]);
                files[i].delete();
            }
            //如果文件本身就是目录 ，就要删除目录
            if (file.exists())
                file.delete();
        }
        LOGGER.info("删除文件夹下的文件结束===");
    }

    /**
     * 云服务文件夹删除
     *
     * @param cosPath 文件名称包含相对路径
     * @param user    用户信息
     * @return 返回结果
     */
    @Override
    public void deleteRemotdFile(String cosPath, User user) {
        LOGGER.info("删除云服务文件夹开始===cospath===" + cosPath + "===user===" + user);
        COSClient cosClient = cosConfig.getCosClient(tenanPropertyService, user);
        ListFolderRequest listFolderRequest = new ListFolderRequest(cosConfig.bucketName, cosPath);
        try {
            String listFolder = cosClient.listFolder(listFolderRequest);
            System.out.println(listFolder);
            JSONObject jsonObject = JSONObject.fromObject(listFolder);
            if ((jsonObject.get("code").toString()).equals("-1")) {
                return;
            }
            JSONObject dataJson = jsonObject.getJSONObject("data");
            JSONArray jsonArray = dataJson.getJSONArray("infos");
            if (jsonArray.size() == 0) return;
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject dir = (JSONObject) jsonArray.get(i);
                String asString = dir.get("name").toString();
                String subcosPath = cosPath + asString + "/";
                DelFileRequest delFileRequest = new DelFileRequest(cosConfig.bucketName, cosPath + asString);
                String delFile = cosClient.delFile(delFileRequest);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info("异常信息是" + e);
        }
        LOGGER.info("删除云服务文件夹结束===cospath===" + cosPath + "===user===" + user);
    }

    /**
     * 下载txt文件，并转存服务器
     *
     * @param list
     * @param serverType 服务器别名
     */
    @Override
    public void downloadTxT(List<Filetable> list, String serverType) {
        LOGGER.info("下载txt文件，并转存服务器开始 文件id" + list + "服务器别名" + serverType);
        Session session = null;
        Channel channel = null;
        try {
            String localPath = "";
            String ftpHost = "";
            int ftpport = 0;
            String ftpUserName = "";
            String ftpPassword = "";
            String servicepath = "";
            String[] serverlist;
            if ("prod".equals(serverType)) {
                serverlist = new String[]{"219", "232"};
            } else {
                serverlist = new String[]{"dev"};
            }

            for (String server : serverlist) {
                if ("219".equals(server)) {
                    localPath = Constants.REALPATH_219;
                    ftpHost = Constants.SERVER_PATH_219;
                    ftpport = Constants.SERVIER_PORT_219;
                    ftpUserName = Constants.SERVER_NAME_219;
                    ftpPassword = Constants.SERVER_PWD_219;
                    //服务器地址
                    servicepath = Constants.SERVIER_PATH_219;
                } else if ("232".equals(server)) {
                    localPath = Constants.REALPATH_232;
                    ftpHost = Constants.SERVER_PATH_232;
                    ftpport = Constants.SERVIER_PORT_232;
                    ftpUserName = Constants.SERVER_NAME_232;
                    ftpPassword = Constants.SERVER_PWD_232;
                    //服务器地址
                    servicepath = Constants.SERVIER_PATH_232;
                } else {
                    localPath = Constants.REALPATH;
                    ftpHost = Constants.SERVER_PATH;
                    ftpport = Constants.SERVIER_PORT;
                    ftpUserName = Constants.SERVER_NAME;
                    ftpPassword = Constants.SERVER_PWD;
                    //服务器地址
                    servicepath = Constants.SERVIER_PATH;
                }
                JSch jsch = new JSch(); // 创建JSch对象
                // 根据用户名，主机ip，端口获取一个Session对象
                session = jsch.getSession(ftpUserName, ftpHost, ftpport);
                if (ftpPassword != null) {
                    // 设置密码
                    session.setPassword(ftpPassword);
                }
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                // 为Session对象设置properties
                session.setConfig(config);
                // 通过Session建立链接
                session.connect();
                // 打开SFTP通道
                channel = session.openChannel("sftp");
                // 建立SFTP通道的连接
                channel.connect();
                ChannelSftp sftp = (ChannelSftp) channel;
                sftp.cd(servicepath);
                List<String> Tenanidlist = new ArrayList<>();
                for (Filetable filetable : list) {
                    if (filetable.getDelflg() == 0) {
                        User user = new User();
                        user.setId(filetable.getUserid());
                        user.setTenanid(filetable.getTenanid());
                        String txtRealPath = filetable.getRemotepath().substring(filetable.getRemotepath().lastIndexOf("/") + 1);
                        String path = "/txt/" + txtRealPath;
                        // 腾讯云对象存储COS调用
                        COSClient cos = cosConfig.getCosClient(tenanPropertyService, user);
                        GetFileInputStreamRequest getFileInputStreamRequest = new GetFileInputStreamRequest(
                                cosConfig.bucketName,
                                path);
                        InputStream input = cos.getFileInputStream(getFileInputStreamRequest);
                        LOGGER.info("====获取文件成功====");
                        File file = new File(localPath + "upload/" + filetable.getTenanid());
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        String folderpath = localPath + "upload/" + filetable.getTenanid() + "/";
                        Tenanidlist.add(folderpath);
                        String filepath = localPath + "upload/" + filetable.getTenanid() + "/" + txtRealPath;

                        LOGGER.info("filepath" + filepath);
                        FileUtils.write(new File(filepath), "");
                        FileOutputStream os = new FileOutputStream(filepath);
                        byte[] buffer = new byte[1024];
                        int n = 0;
                        while (-1 != (n = input.read(buffer))) {
                            os.write(buffer, 0, n);
                        }
                        os.flush();
                        os.close();
                        input.close();
                    } else {
                        String txtRealPath = filetable.getRemotepath().substring(filetable.getRemotepath().lastIndexOf("/") + 1);
                        sftp.rm(filetable.getTenanid() + "/" + txtRealPath);
                    }
                }
                Set set = new HashSet();
                List newList = new ArrayList();
                for (String cd : Tenanidlist) {
                    if (set.add(cd)) {
                        newList.add(cd);
                    }
                }
                LOGGER.info("去重后的集合： " + newList);
                for (Object tenanFolderPath : newList) {
                    SFTPUtils.upLoadFile(session, tenanFolderPath.toString(), servicepath);
                    this.deleteAllFile(new File(tenanFolderPath.toString()));
                }
                session.disconnect();
                channel.disconnect();
            }
            LOGGER.info("下载txt文件，并转存服务器结束");
        } catch (Exception e) {
            LOGGER.info("连接异常" + e);
            e.printStackTrace();
        } finally {
            LOGGER.info("关闭服务===");
            session.disconnect();
            channel.disconnect();
        }
    }

    /**
     * 下载html文件，并转存服务器
     *
     * @param list
     * @param serverType 服务器类别
     */
    @Override
    public void downloadHTML(List<Filetable> list, String serverType) {
        LOGGER.info("下载html文件，并转存服务器开始 文件id" + list +
                "服务器类别" + serverType);
        Session session = null;
        Channel channel = null;
        try {
            String localPath = "";
            String ftpHost = "";
            int ftpport = 0;
            String ftpUserName = "";
            String ftpPassword = "";
            String servicepath = "";
            if ("219".equals(serverType)) {
                localPath = Constants.REALPATH_219;
                ftpHost = Constants.PAGE_SERVER_PATH_219;
                ftpport = Constants.PAGE_SERVER_PORT_219;
                ftpUserName = Constants.PAGE_SERVER_NAME_219;
                ftpPassword = Constants.PAGE_SERVER_PWD_219;
                //服务器地址
                servicepath = Constants.REALPATH_219 + "upload/";
            } else if ("232".equals(serverType)) {
                localPath = Constants.REALPATH_232;
                ftpHost = Constants.PAGE_SERVER_PATH_232;
                ftpport = Constants.PAGE_SERVER_PORT_232;
                ftpUserName = Constants.PAGE_SERVER_NAME_232;
                ftpPassword = Constants.PAGE_SERVER_PWD_232;
                //服务器地址
                servicepath = Constants.REALPATH_232 + "upload/";
            } else {
                localPath = Constants.REALPATH;
                ftpHost = Constants.PAGE_SERVER_PATH;
                ftpport = Constants.PAGE_SERVER_PORT;
                ftpUserName = Constants.PAGE_SERVER_NAME;
                ftpPassword = Constants.PAGE_SERVER_PWD;
                //服务器地址
                servicepath = Constants.REALPATH + "upload/";
            }
            // 创建JSch对象
            JSch jsch = new JSch();
            // 根据用户名，主机ip，端口获取一个Session对象
            session = jsch.getSession(ftpUserName, ftpHost, ftpport);
            if (ftpPassword != null) {
                // 设置密码
                session.setPassword(ftpPassword);
            }
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            // 为Session对象设置properties
            session.setConfig(config);
            // 通过Session建立链接
            session.connect();
            // 打开SFTP通道
            channel = session.openChannel("sftp");
            // 建立SFTP通道的连接
            channel.connect();
            ChannelSftp sftp = (ChannelSftp) channel;
            sftp.cd(servicepath);
            //进入服务器指定的文件夹
            List<String> htmlnameList = new ArrayList<>();
            //列出服务器指定的文件列表
            Vector v = sftp.ls("*.html");
            for (int i = 0; i < v.size(); i++) {
                //判断该名字的文件在文件夹里是否存在
                htmlnameList.add(v.get(i).toString());
            }
            //存放html文件夹路径
            String tenanFolderPath = null;
            for (Filetable filetable : list) {
                if (filetable.getDelflg() == 0) {
                    User user = new User();
                    user.setId(filetable.getUserid());
                    user.setTenanid(filetable.getTenanid());
                    String htmlRealPath = filetable.getRemotepath().substring(filetable.getRemotepath().lastIndexOf("/") + 1);
                    if (htmlnameList.contains(htmlRealPath)) {
                        continue;
                    }
                    String path = "/html/" + htmlRealPath;
                    // 腾讯云对象存储COS调用
                    COSClient cos = cosConfig.getCosClient(tenanPropertyService, user);
                    GetFileInputStreamRequest getFileInputStreamRequest = new GetFileInputStreamRequest(
                            cosConfig.bucketName,
                            path);
                    InputStream input = cos.getFileInputStream(getFileInputStreamRequest);
                    LOGGER.info("====获取文件成功====");
                    File file = new File(localPath + "upload/" + "html/");
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    String folderpath = localPath + "upload/" + "html/";
                    tenanFolderPath = folderpath;
                    String filepath = localPath + "upload/" + "html/" + htmlRealPath;
                    LOGGER.info("filepath" + filepath);
                    FileUtils.write(new File(filepath), "");
                    FileOutputStream os = new FileOutputStream(filepath);
                    byte[] buffer = new byte[1024];
                    int n = 0;
                    while (-1 != (n = input.read(buffer))) {
                        os.write(buffer, 0, n);
                    }
                    os.flush();
                    os.close();
                    input.close();
                } else {
                    String htmlRealPath = filetable.getRemotepath().substring(filetable.getRemotepath().lastIndexOf("/") + 1);
                    String path = "html/" + htmlRealPath;
                    sftp.rm(path);
                }
            }
//            if(tenanFolderPath != null) {
//                SFTPUtils.upLoadFile( session, tenanFolderPath, servicepath );
//                this.deleteAllFile( new File( tenanFolderPath ) );
//            }
            LOGGER.info("下载html文件，并转存服务器结束");
        } catch (Exception e) {
            LOGGER.info("连接异常" + e);
            e.printStackTrace();
        } finally {
            LOGGER.info("关闭服务===");
            session.disconnect();
            channel.disconnect();
        }
    }

    /**
     * 远端链接
     *
     * @param htmlPath 文件的目录
     */
    @Override
    public void remoteConnection(String htmlPath) {
        Session session = null;
        Channel channel = null;
        String ftpHost = "";
        int ftpport = 0;
        String ftpUserName = "";
        String ftpPassword = "";
        // 创建JSch对象
        //prod
//        String[] serverIpArray= new String[]{"219","232"};
        //dev
        String[] serverIpArray = new String[]{"dev"};
        for (String str : serverIpArray) {
            JSch jsch = new JSch();
            try {
                // 根据用户名，主机ip，端口获取一个Session对象
                if ("219".equals(str)) {
                    ftpHost = Constants.PAGE_SERVER_PATH_219;
                    ftpport = Constants.PAGE_SERVER_PORT_219;
                    ftpUserName = Constants.PAGE_SERVER_NAME_219;
                    ftpPassword = Constants.PAGE_SERVER_PWD_219;
                } else if ("232".equals(str)) {
                    ftpHost = Constants.PAGE_SERVER_PATH_232;
                    ftpport = Constants.PAGE_SERVER_PORT_232;
                    ftpUserName = Constants.PAGE_SERVER_NAME_232;
                    ftpPassword = Constants.PAGE_SERVER_PWD_232;
                } else {
                    ftpHost = Constants.PAGE_SERVER_PATH;
                    ftpport = Constants.PAGE_SERVER_PORT;
                    ftpUserName = Constants.PAGE_SERVER_NAME;
                    ftpPassword = Constants.PAGE_SERVER_PWD;
                }
                session = jsch.getSession(ftpUserName, ftpHost, ftpport);
                if (ftpPassword != null) {
                    // 设置密码
                    session.setPassword(ftpPassword);
                }
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                // 为Session对象设置properties
                session.setConfig(config);
                // 通过Session建立链接
                session.connect();
                // 打开SFTP通道
                channel = session.openChannel("sftp");
                // 建立SFTP通道的连接
                channel.connect();
                ChannelSftp sftp = (ChannelSftp) channel;
                //进入服务器指定的文件夹
                String servicepath = "/mnt/wcm/upload/";
                SFTPUtils.upLoadFile(session, htmlPath, servicepath);
            } catch (JSchException e) {
                LOGGER.info("服务上传异常");
                e.printStackTrace();
            } finally {
                LOGGER.info("关闭服务===");
                session.disconnect();
                channel.disconnect();
            }
        }
    }

    /**
     * 字符串写入html
     *
     * @param tempFile 写入的地址
     * @param dest     字符串
     */
    @Override
    public void writeFile(String tempFile, String dest) {
        try {
            ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(dest.getBytes());
            InputStream input = tInputStringStream;
            FileOutputStream os = new FileOutputStream(tempFile);
            byte[] buffer = new byte[1024];
            int n = 0;
            while (-1 != (n = input.read(buffer))) {
                os.write(buffer, 0, n);
            }
            os.flush();
            os.close();
            input.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 获取数据库文件对象
     * 业务：通过filetable的元素查询对象返回
     *
     * @param filetable
     * @return
     */
    @Override
    public Filetable getFiletable(Filetable filetable) {
        LOGGER.info("通过文件id查看文件开始 文件Id=" + filetable.getId());
        Filetable filetableMessage = fileTableDao.selectOne(filetable);
        LOGGER.info("通过文件id查看文件结束");
        return filetableMessage;
    }

    /**
     * 彻底删除文件信息
     * 业务：彻底从数据库删除文件信息
     *
     * @param filetable
     */
    @Override
    public void deleteFileThorough(Filetable filetable) {
        Example example = new Example(Filetable.class);
        LOGGER.info("表数据删除方法开始 文件id" + filetable.getId());
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", filetable.getId());
        LOGGER.info("表数据删除方法结束");
        fileTableDao.deleteByExample(example);
    }

    /**
     * 删除html文件
     * 业务:将delflg改为1，网页管理不显示
     *
     * @param filetable
     */
    @Override
    public void deleteHtml(Filetable filetable) {
        LOGGER.info("删除html文件开始 文件id" + filetable.getId());
        filetable.setUpdatetime(new Date());
        fileTableDao.deleteHtml(filetable);
        LOGGER.info("删除html文件");
    }

    /**
     * 上传html所带的txt
     *
     * @param htmlStr  html的字符串
     * @param filename html的名字
     * @param uuid     html的uuid
     * @param user     用户信息
     */
    @Override
    public void uploadOrginalTxt(String htmlStr, String filename, String uuid, User user) {
        LOGGER.info("进入到上传txt的方法==" + "==filename==" + filename + "==uuid==" + uuid);
        //把传过来的html字符串的转成txt
        String oldclean = Jsoup.clean(htmlStr, Whitelist.none());
        String newClean = oldclean.replaceAll(" ", "\r\n");
        //LOGGER.info("newClean"+newClean);
        String remotePath = Util.wcmserver + "/html/" + uuid ;
        //通过远端路径获取对象
        Filetable f = new Filetable();
        f.setRemotepath(remotePath);
        Filetable filetable = fileTableDao.selectOne(f);
        //获取到原始html的文件目录
        String localpath = filetable.getLocalpath();
        String newFileName = filename;
        if (filename.contains(".")) {
            newFileName = filename.substring(0, filename.lastIndexOf("."));
        }
        //写入的路径
        String outPath = Constants.REALPATH + "upload" + "/file/" + localpath + newFileName + ".txt";
        File oldfile = new File(Constants.REALPATH + "upload" + "/file/" + localpath);
        if (!oldfile.exists()) {
            oldfile.mkdirs();
        }
        LOGGER.info("本地文件路径==" + outPath);
        //写入到本地
        Util.writeFile(newFileName + "\r\n" + Constants.SERVERPATH + "/" + "upload/html/" + uuid + ".html" + "\r\n" + newClean, outPath, true);
        //上传到云存储。
        this.uploadConvert(outPath, Constants.REALPATH, user);
        //删除掉这个文件
        File file = new File(outPath);
        file.delete();
        LOGGER.info("上传txt的方法结束===");
    }

    /**
     * 流转成String
     * 业务:将流内信息转换成html字符串
     *
     * @param inputStream
     * @return
     */
    @Override
    public String getHTMLTEXT(InputStream inputStream) {
        LOGGER.info("流转成String开始");
        // 自带缓存的输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = -1;
        byte[] buffer = new byte[512];
        try {
            while ((len = inputStream.read(buffer)) != -1) {
                // 将读到的字节，写入baos
                baos.write(buffer, 0, len);
            }
            //LOGGER.info("流转成String结束" + new String(baos.toByteArray()));
            return new String(baos.toByteArray());
        } catch (IOException e) {
            LOGGER.info("流转成String 转换异常" + e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除txt信息
     *
     * @param htmlMessage
     */
    @Override
    public void deleteTxt(Filetable htmlMessage) {
        LOGGER.info("删除txt信息开始 文件名称" + htmlMessage.getFilename());
        Filetable filetable = new Filetable();
        filetable.setUserid(htmlMessage.getUserid());
        filetable.setFilename(htmlMessage.getFilename());
        filetable.setLocalpath(htmlMessage.getLocalpath());
        filetable.setSuffix("txt");
        Filetable textMessage = fileTableDao.selectOne(filetable);
        //逻辑删除html
        fileTableDao.deleteHtml(textMessage);
        LOGGER.info("删除txt信息结束");
    }
}


